package com.ryzx.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;

public class JsonUtil {
    private static final ObjectMapper objectMapper=new ObjectMapper();
    public static String obj2String(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            return null;
        }
    }
    public static <T> T String2obj(String s,Class<T> valueType){
        try {
            return objectMapper.readValue(s,valueType);
        } catch (JsonProcessingException e) {
            return null;
        }
    }
    public static <T> T String2obj(String s,TypeReference<T> t){
        try {
            return objectMapper.readValue(s,t);
        } catch (JsonProcessingException e) {
            return null;
        }
    }
//    public static <T> T String2obj(String str) throws InstantiationException, IllegalAccessException, NoSuchFieldException {
//        T t;
//        Class<T> cls=(Class<T>) ((ParameterizedType) JsonUtil.class.getGenericSuperclass()).getActualTypeArguments()[0];
//        t=cls.newInstance();
//
//        HashMap<String,Object> hm=String2HashMap(str);
//        for (String s:hm.keySet()) {
//            Field f=t.getClass().getDeclaredField(s);
//            f.setAccessible(true);
//            f.set(t,hm.get(s));
//        }
//        return t;
//    }
    public static HashMap<String,Object> String2HashMap(String s){
        try {
            return objectMapper.readValue(s, new TypeReference<>(){});
        } catch (JsonProcessingException e) {
            return null;
        }
    }


}
